/**
 * @author banglong
 * @date 2016/10/11
 */
define(['avalon', 'Layer', 'tools', 'getVmConfig', 'chooseCondition', 'rootPath',
    'text!../html/index/report/booksapplyanalyzeTemp.html!strip', 'depsSelectDialog', 'GoodsSelectDialog',
    'booksApplyAnalyzeApi', 'text!../html/index/report/singleDeptApplyTemp.html!strip',
    'text!../html/index/report/goodsBookApplyTemp.html!strip', 'text!../html/index/report/packageDrawQueryTemp.html!strip',
    'text!../html/index/report/packageDrawQueryDetailTemp.html!strip', 'Condition', 'laydate'
  ],
  function (avalon, layer, tools, getVmConfig, chooseCondition, rootPath, htmlTemp, depsSelectDialog, GoodsSelectDialog,
    api, singleDeptApplyTemp, goodsBookApplyTemp, packageDrawQuery, packageDrawQueryDetailTemp, Condition) {

    var runtimeParam;
    var getRuntimeParam = function () {
      return {
        showMenu: {},
        checkBreadcrumb: {},
        Openparm: {},
        providerDept: {},
        currentDept: {},
        goods: [],
        excelParam: {},
        packageDrawDetailParam: {},
        timeObj: {}
      };
    };

    var booksApplyAnalyzeVm;
    var getVmOption = function () {
      return {
        $id: 'booksApplyAnalyze',
        breadcrumb: '',
        isProviderDept: false,
        reportType: '',

        startTime: '',
        endTime: '',
        deptAccountName: '',
        deptAccountID: '',
        goodsBookName: '',
        goodsBookID: '',

        packageBigID: '%',
        packageBigList: [],

        goodsName: '',
        goodsID: '',
        goodsNo: '',

        goods: [],
        packageDrawDetail: [],
        title: '',
        localStartTime: '',
        localEndTime: '',

        size: 50,
        pages: 1,
        counts: 1,

        // 是否显示 病区领用 详情
        isShowPackageDrawDetail: false,
        // 各个按钮的 class 属性
        firstPages: 'disabled',
        lastPages: 'disabled',
        prePages: 'disabled',
        nextPages: 'disabled',
        backPreReport: 'disabled',

        back: function () {
          var main = document.querySelector('#main');
          main.removeChild(tools.getFirstElementChild(main));
          runtimeParam.checkBreadcrumb();
          runtimeParam.showMenu();
        },

        print: function () {
          // todo 打印效果调整
          var headstr = '<html><head></head><link rel="stylesheet" href="css/common/bootstrap.min.css"/> <link rel="stylesheet" href="css/pages/index.css"/>' + '<body><br/><br/><br/>';
          var footstr = "</body>";
          var printHtml = headstr + document.querySelector('#reportContent').innerHTML + footstr;
          var oldstr = document.body.removeChild(document.querySelector('#container'));
          document.body.innerHTML = printHtml;
          window.print();
          document.body.innerHTML = '';
          document.body.appendChild(oldstr);
          return false;
        },

        search: function () {
          if (!booksApplyAnalyzeVm.deptAccountID && booksApplyAnalyzeVm.reportType === 'booksapplyanalyze') {
            tools.handleError('请选择科室');
            return;
          }
          // if (!booksApplyAnalyzeVm.goodsBookID && booksApplyAnalyzeVm.reportType === 'wardapplyanalyze') {
          //     tools.handleError('请选择账册');
          //     return;
          // }
          // 根据访问报表的不同 来设置不同的查询条件
          getReportDataCondition(booksApplyAnalyzeVm);

          var layerIndex = layer.load();
          booksApplyAnalyzeVm.pages = 1;
          api.getDeptApplyAnalyze(runtimeParam.excelParam).then(function (jsonResult) {
            if (jsonResult.issuccess !== 0) {
              return Promise.reject('获取信息失败');
            }

            var result = JSON.parse(jsonResult.result);
            if (booksApplyAnalyzeVm.reportType === 'booksapplyanalyze') {
              runtimeParam.goods = handleReportForSingleDept(result);
            } else if (booksApplyAnalyzeVm.reportType === 'wardapplyanalyze') {
              runtimeParam.goods = handleReportForGoodsBook(result);
            } else if (booksApplyAnalyzeVm.reportType === 'packagedrawquery') {
              runtimeParam.goods = handleReportForPackageDrawQuery(result);
            }
            paging(booksApplyAnalyzeVm, booksApplyAnalyzeVm.goods, runtimeParam.goods, booksApplyAnalyzeVm.size);

            booksApplyAnalyzeVm.localStartTime = booksApplyAnalyzeVm.startTime.replace('-', '年')
              .replace('-', '月') + '日';
            booksApplyAnalyzeVm.localEndTime = booksApplyAnalyzeVm.endTime.replace('-', '年')
              .replace('-', '月') + '日';
            booksApplyAnalyzeVm.title = booksApplyAnalyzeVm.localStartTime + "至" + booksApplyAnalyzeVm.localEndTime;
            switch (booksApplyAnalyzeVm.reportType) {
              case 'booksapplyanalyze':
                booksApplyAnalyzeVm.title += '单一科室所有账册查询';
                break;
              case 'wardapplyanalyze':
                booksApplyAnalyzeVm.title += '病区领用单报表';
                break;
              case 'packagedrawquery':
                booksApplyAnalyzeVm.title += '领用明细报表';
                break;
            }
            layer.close(layerIndex);

          })['catch'](function (ex) {
            layer.close(layerIndex);
            tools.handleError(ex);
          });
        },

        chooseDept: function (e) {
          var theEvent = e || window.event;
          var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
          if (code !== 13) {
            return;
          }

          // 科室选择框
          var deps = JSON.parse(localStorage.getItem('deps'));
          depsSelectDialog.init(deps,
            function (dep) {
              booksApplyAnalyzeVm.deptAccountName = dep.Ksmc.trim();
              booksApplyAnalyzeVm.deptAccountID = dep.Ksdm;
            },
            booksApplyAnalyzeVm.deptAccountName);
        },

        chooseGoodsBook: function (e) {
          var theEvent = e || window.event;
          var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
          if (code !== 13) {
            return;
          }

          // 科室选择框
          var param = {
            type: 1
          };
          param.chooseConditionsFunc = function (condition) {
            booksApplyAnalyzeVm.goodsBookName = condition.GoodsBookName;
            booksApplyAnalyzeVm.goodsBookID = condition.GoodsBookID;
          };
          param.searchValue = booksApplyAnalyzeVm.goodsBookName;
          chooseCondition.init(param);
        },

        exportExcel: function () {
          if (booksApplyAnalyzeVm.goods.length <= 1) {
            tools.handleError("请确认查询结果不为空");
            return;
          }

          // 导出excel
          var url;
          if (booksApplyAnalyzeVm.reportType === 'booksapplyanalyze') {
            url = rootPath.getRootPath() + "export/singleDeptApply";
          } else if (booksApplyAnalyzeVm.reportType === 'wardapplyanalyze') {
            url = rootPath.getRootPath() + "export/goodsBookExcel";
          } else if (booksApplyAnalyzeVm.reportType === 'packagedrawquery') {
            if (booksApplyAnalyzeVm.isShowPackageDrawDetail) {
              url = rootPath.getRootPath() + "export/goodsPackageDrawQueryDetailExcel";
            } else {
              url = rootPath.getRootPath() + "export/goodsPackageDrawQueryExcel";
            }
          }

          // 查看详情 不一样的存放位置
          var data = {};
          if (!booksApplyAnalyzeVm.isShowPackageDrawDetail) {
            url += '?providerDeptAccountID=' + encodeURIComponent(encodeURIComponent(runtimeParam.excelParam.providerDeptAccountID));
            data.providerDeptAccountID = encodeURIComponent(runtimeParam.excelParam.providerDeptAccountID);
            url += '&className=' + encodeURIComponent(encodeURIComponent(runtimeParam.excelParam.className));
            data.className = runtimeParam.excelParam.className;
            url += '&method=' + encodeURIComponent(encodeURIComponent(runtimeParam.excelParam.method));
            data.method = runtimeParam.excelParam.method;
            url += '&startTime=' + encodeURIComponent(encodeURIComponent(runtimeParam.excelParam.startTime));
            data.startTime = runtimeParam.excelParam.startTime;
            url += '&endTime=' + encodeURIComponent(encodeURIComponent(runtimeParam.excelParam.endTime));
            data.endTime = runtimeParam.excelParam.endTime;
          }

          switch (booksApplyAnalyzeVm.reportType) {
            case "booksapplyanalyze":
              url += '&applyDeptID=' + encodeURIComponent(encodeURIComponent(runtimeParam.excelParam.applyDeptID));
              data.applyDeptID = encodeURIComponent(runtimeParam.excelParam.applyDeptID);
              url += '&name=' + encodeURIComponent(encodeURIComponent(booksApplyAnalyzeVm.title));
              data.name = booksApplyAnalyzeVm.title;
              url += '&fieldName=' + encodeURIComponent(encodeURIComponent(['账户号', '账户名称', '账册', '物品代码', '物品名称', '规格', '单位', '单价', '数量', '金额', '卡片号', '收费代码'].join(',')));
              data.fieldName = ['账户号', '账户名称', '账册', '物品代码', '物品名称', '规格', '单位', '单价', '数量', '金额', '卡片号', '收费代码'].join(',');
              url += '&fieldValueName=' + encodeURIComponent(encodeURIComponent(['MAXDeptAccountName', 'MAXDeptAccountName', 'MAXGoodsBookName', 'GoodsID', 'MAXGoodName', 'MAXGoodsSpec', 'MAXBoxUnit', 'LatestPrice', 'MAXCount', 'MAXAmount', 'MAXCardNumber', 'MAXChargeCode'].join(',')));
              data.fieldValueName = ['MAXDeptAccountName', 'MAXDeptAccountName', 'MAXGoodsBookName', 'GoodsID', 'MAXGoodName', 'MAXGoodsSpec', 'MAXBoxUnit', 'LatestPrice', 'MAXCount', 'MAXAmount', 'MAXCardNumber', 'MAXChargeCode'].join(',');
              break;
            case 'wardapplyanalyze':
              url += '&deptAccountID=' + encodeURIComponent(encodeURIComponent(runtimeParam.excelParam.deptAccountID));
              data.deptAccountID = encodeURIComponent(runtimeParam.excelParam.deptAccountID);
              url += '&goodsBookID=' + encodeURIComponent(encodeURIComponent(runtimeParam.excelParam.goodsBookID));
              data.goodsBookID = encodeURIComponent(runtimeParam.excelParam.goodsBookID);
              url += '&name=' + encodeURIComponent(encodeURIComponent(booksApplyAnalyzeVm.title));
              data.name = booksApplyAnalyzeVm.title;
              url += '&fieldName=' + encodeURIComponent(encodeURIComponent(['账户号', '账户名称', '物品代码', '物品名称', '规格', '单位', '单价', '数量', '金额', '卡片号'].join(',')));
              data.fieldName = ['账户号', '账户名称', '物品代码', '物品名称', '规格', '单位', '单价', '数量', '金额', '卡片号'].join(',');
              url += '&fieldValueName=' + encodeURIComponent(encodeURIComponent(['MAXDeptAccountName', 'MAXDeptAccountName', 'GoodsID', 'MAXGoodName', 'MAXGoodsSpec', 'MAXBoxUnit', 'LatestPrice', 'MAXCount', 'MAXAmount', 'MAXCardNumber'].join(',')));
              data.fieldValueName = ['MAXDeptAccountName', 'MAXDeptAccountName', 'GoodsID', 'MAXGoodName', 'MAXGoodsSpec', 'MAXBoxUnit', 'LatestPrice', 'MAXCount', 'MAXAmount', 'MAXCardNumber'].join(',');
              break;
            case 'packagedrawquery':
              if (!booksApplyAnalyzeVm.isShowPackageDrawDetail) {
                url += '&packageID=' + encodeURIComponent(encodeURIComponent(runtimeParam.excelParam.packageID));
                data.packageID = encodeURIComponent(runtimeParam.excelParam.packageID);
                url += '&packageBigID=' + encodeURIComponent(encodeURIComponent(runtimeParam.excelParam.packageBigID));
                data.packageBigID = encodeURIComponent(runtimeParam.excelParam.packageBigID);
                url += '&deptID=' + encodeURIComponent(encodeURIComponent(runtimeParam.excelParam.deptID));
                data.deptID = encodeURIComponent(runtimeParam.excelParam.deptID);
                url += '&goodsNo=' + encodeURIComponent(encodeURIComponent(runtimeParam.excelParam.goodsNo));
                data.goodsNo = encodeURIComponent(runtimeParam.excelParam.goodsNo);
                url += '&name=' + encodeURIComponent(encodeURIComponent(booksApplyAnalyzeVm.title));
                data.name = booksApplyAnalyzeVm.title;
                url += '&fieldName=' + encodeURIComponent(encodeURIComponent(['科室名称', '物品代码', '物品名称', '拆零单位', '单价', '数量', '金额'].join(',')));
                data.fieldName = ['科室名称', '物品代码', '物品名称', '拆零单位', '单价', '数量', '金额'].join(',');
                url += '&fieldValueName=' + encodeURIComponent(encodeURIComponent(['DeptName', 'PackageCode', 'PackageName', 'Unit', 'Price', 'Counts', 'Amount'].join(',')));
                data.fieldValueName = ['DeptName', 'PackageCode', 'PackageName', 'Unit', 'Price', 'Counts', 'Amount'].join(',');
              } else {
                url += '?className=' + encodeURIComponent(encodeURIComponent(runtimeParam.packageDrawDetailParam.className));
                data.className = runtimeParam.packageDrawDetailParam.className;
                url += '&startTime=' + encodeURIComponent(encodeURIComponent(runtimeParam.excelParam.startTime));
                data.startTime = encodeURIComponent(runtimeParam.excelParam.startTime);
                url += '&endTime=' + encodeURIComponent(encodeURIComponent(runtimeParam.excelParam.endTime));
                data.endTime = runtimeParam.excelParam.endTime;
                url += '&method=' + encodeURIComponent(encodeURIComponent(runtimeParam.packageDrawDetailParam.method));
                data.method = runtimeParam.packageDrawDetailParam.method;
                url += '&packageID=' + encodeURIComponent(encodeURIComponent(runtimeParam.packageDrawDetailParam.packageID));
                data.packageID = encodeURIComponent(runtimeParam.packageDrawDetailParam.packageID);
                url += '&deptID=' + encodeURIComponent(encodeURIComponent(runtimeParam.packageDrawDetailParam.deptID));
                data.deptID = encodeURIComponent(runtimeParam.packageDrawDetailParam.deptID);
                url += '&name=' + encodeURIComponent(encodeURIComponent(booksApplyAnalyzeVm.title));
                data.name = booksApplyAnalyzeVm.title;
                url += '&fieldName=' + encodeURIComponent(encodeURIComponent(['物品代码', '物品名称', '单价', '数量', '货号', '有效期起', '有效期止'].join(',')));
                data.fieldName = ['物品代码', '物品名称', '单价', '数量', '货号', '有效期起', '有效期止'].join(',');
                url += '&fieldValueName=' + encodeURIComponent(encodeURIComponent(['PackageCode', 'PackageName', 'Price', 'Counts', 'GoodsNo', 'Yxqq', 'Yxqz'].join(',')));
                data.fieldValueName = ['PackageCode', 'PackageName', 'Price', 'Counts', 'GoodsNo', 'Yxqq', 'Yxqz'].join(',');
              }
              break;
          }

          if (tools.isIEByActiveObject()) {
            tools.DownLoadFile({
              url: url.split('?')[0],
              data: data
            });
          } else {
            window.location.href = url;
          }
        },

        handlePagesInput: function () {
          tools.throttle(runtimeParam.timeObj, function () {
            var pages = parseInt(booksApplyAnalyzeVm.pages);
            if (booksApplyAnalyzeVm.goods.length === 0) {
              booksApplyAnalyzeVm.pages = 1;
              return;
            }
            if (!booksApplyAnalyzeVm.isShowPackageDrawDetail && !isNaN(pages)) {
              if (pages > 1 && booksApplyAnalyzeVm.pages < booksApplyAnalyzeVm.counts) {
                paging(booksApplyAnalyzeVm, booksApplyAnalyzeVm.goods, runtimeParam.goods, booksApplyAnalyzeVm.size);
              } else {
                booksApplyAnalyzeVm.pages = 1;
                paging(booksApplyAnalyzeVm, booksApplyAnalyzeVm.goods, runtimeParam.goods, booksApplyAnalyzeVm.size);
              }
            }
          });
        },

        jumpPageing: function (type) {
          if (!booksApplyAnalyzeVm.isShowPackageDrawDetail) {
            var pages = booksApplyAnalyzeVm.pages;
            switch (type) {
              case 0:
                if (booksApplyAnalyzeVm.pages !== 1) {
                  booksApplyAnalyzeVm.pages = 1;
                }
                break;
              case 1:
                if (booksApplyAnalyzeVm.pages > 1) {
                  booksApplyAnalyzeVm.pages--;
                }
                break;
              case 2:
                if (booksApplyAnalyzeVm.pages < booksApplyAnalyzeVm.counts) {
                  booksApplyAnalyzeVm.pages++;
                }
                break;
              case 3:
                if (booksApplyAnalyzeVm.pages < booksApplyAnalyzeVm.counts) {
                  booksApplyAnalyzeVm.pages = booksApplyAnalyzeVm.counts;
                }
                break;
            }
            if (pages !== booksApplyAnalyzeVm.pages && runtimeParam.goods.length > 0) {
              paging(booksApplyAnalyzeVm, booksApplyAnalyzeVm.goods, runtimeParam.goods, booksApplyAnalyzeVm.size);
            }
          }
        },

        chooseGoods: function (e) {
          var theEvent = e || window.event;
          var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
          if (code !== 13) {
            return;
          }

          new GoodsSelectDialog().init({
            Openparm: runtimeParam.Openparm,
            isGYKS: true,
            getAll: true,
            searchValue: booksApplyAnalyzeVm.goodsName, //初始的查询信息
            pushChooseGoods: function (data) { // 选择物品
              booksApplyAnalyzeVm.goodsName = data.GoodsName;
              booksApplyAnalyzeVm.goodsID = data.GoodsID;
            }
          });
        },

        showPackageDrawDetail: function (index) {

          var good = booksApplyAnalyzeVm.goods[index];
          var layerIndex = layer.load();
          runtimeParam.packageDrawDetailParam = {
            className: 'ReportFormManager',
            method: 'GetPackageDrawDetail',
            packageID: good.PackageID,
            deptID: good.DeptID,
            startDate: booksApplyAnalyzeVm.startTime,
            endDate: booksApplyAnalyzeVm.endTime
          };
          api.getPackageDrawDetail(runtimeParam.packageDrawDetailParam).then(function (jsonResult) {
            if (jsonResult.issuccess !== 0) {
              return Promise.reject('获取信息失败');
            }

            var result = JSON.parse(jsonResult.result);
            result.forEach(function (data) {
              data.Yxqq = new Date(data.Yxqq).format('yyyy-MM-dd');
              data.Yxqz = new Date(data.Yxqz).format('yyyy-MM-dd');
            });

            // 不可翻页
            runtimeParam.canScroll = false;
            booksApplyAnalyzeVm.packageDrawDetail.splice(0, booksApplyAnalyzeVm.packageDrawDetail.length);
            booksApplyAnalyzeVm.packageDrawDetail.pushArray(result);
            booksApplyAnalyzeVm.isShowPackageDrawDetail = true;
            booksApplyAnalyzeVm.backPreReport = 'canclick';

            layer.close(layerIndex);

          })['catch'](function (ex) {
            layer.close(layerIndex);
            tools.handleError(ex);
          })
        },

        backParentReport: function () {
          if (booksApplyAnalyzeVm.isShowPackageDrawDetail) {
            booksApplyAnalyzeVm.isShowPackageDrawDetail = false;
            booksApplyAnalyzeVm.backPreReport = 'disabled';
            runtimeParam.canScroll = true;
          }
        }
      };
    };

    // 根据访问报表的不同来设置不同的查询条件
    function getReportDataCondition(booksApplyAnalyzeVm) {
      runtimeParam.excelParam = {
        className: 'ReportFormManager',
        providerDeptAccountID: runtimeParam.providerDept.DeptAccountID,
        startTime: booksApplyAnalyzeVm.startTime,
        endTime: booksApplyAnalyzeVm.endTime
      };
      // 将结束日期天数加 1
      var n = new Date(booksApplyAnalyzeVm.endTime).getTime() + 24 * 60 * 60 * 1000;
      runtimeParam.excelParam.endTime = new Date(n).format('yyyy-MM-dd');

      if (booksApplyAnalyzeVm.reportType === 'booksapplyanalyze') {
        runtimeParam.excelParam.method = 'GetSingleDeptApplyAnalyze';
        runtimeParam.excelParam.applyDeptID = booksApplyAnalyzeVm.deptAccountID;

      } else if (booksApplyAnalyzeVm.reportType === 'wardapplyanalyze') {
        runtimeParam.excelParam.method = 'GetDeptApplyAnalyze';
        runtimeParam.excelParam.deptAccountID = runtimeParam.currentDept.DeptAccountID;
        runtimeParam.excelParam.goodsBookID = booksApplyAnalyzeVm.goodsBookID || '%';

      } else if (booksApplyAnalyzeVm.reportType === 'packagedrawquery') {
        runtimeParam.excelParam.method = 'GetPackageDrawQuery';
        runtimeParam.excelParam.startDate = booksApplyAnalyzeVm.startTime;
        runtimeParam.excelParam.endDate = booksApplyAnalyzeVm.endTime;
        runtimeParam.excelParam.packageID = booksApplyAnalyzeVm.goodsID || '%';
        runtimeParam.excelParam.packageBigID = booksApplyAnalyzeVm.packageBigID || '%';
        runtimeParam.excelParam.deptID = booksApplyAnalyzeVm.deptAccountID || '%';
        runtimeParam.excelParam.goodsNo = booksApplyAnalyzeVm.goodsNo || '%';
      }
    }

    // 分页
    function paging(vm, vmArr, arr, size, canSlideBootom) {
      vm.counts = arr.length === 0 ? 0 : Math.ceil(arr.length / size);
      var pages = parseInt(vm.pages);
      var truePages = pages - 1;

      vmArr.splice(0, vmArr.length);
      vmArr.pushArray(arr.slice(truePages * size, truePages * size + size));


      if (pages === 1) {
        if (booksApplyAnalyzeVm.counts === 1) {
          setToolsClass('disabled', 'disabled', 'disabled', 'disabled');
        } else {
          setToolsClass('disabled', 'disabled', 'canclick', 'canclick');
        }
      } else if (pages > 1) {
        if (pages < booksApplyAnalyzeVm.counts) {
          setToolsClass('canclick', 'canclick', 'canclick', 'canclick');
        } else {
          setToolsClass('canclick', 'canclick', 'disabled', 'disabled');
        }
      }

      // 判断是否需要滚动到顶端标题
      var reportContent = $('html, #reportContent');
      var reportTitle = $("#reportTitle");
      var tableFooter = $("#tableFooter");
      if (document.querySelector('#reportContent').scrollTop > 0 && !canSlideBootom) {
        reportContent.animate({
          scrollTop: reportTitle.offset().top + 5
        }, 200);
      }
      if (canSlideBootom) {
        reportContent.animate({
          scrollTop: tableFooter.offset().top - 15
        }, 200);
      }

      copyTableThead();
    }

    function copyTableThead() {
      if (document.querySelector('#tablePlaceholder,table,thead').childNodes.length === 0) {
        var $reportThear = $('#reportTable').find('thead tr');
        $reportThear.each(function () {
          //    todo 表头固定

        });
      }
    }

    // 单一科室所有账册 过滤数组 拼接数据
    function handleReportForSingleDept(result) {
      var goods = [];
      var sumCount = 0;
      var sumMoney = 0;
      var allSumCount = 0;
      var allSumMoney = 0;
      var oldGoodsBook = '';
      result.forEach(function (data, index) {
        if (index === 0) {
          oldGoodsBook = data.MAXGoodsBookName;
          sumCount += data.MAXCount;
          sumMoney += data.MAXAmount;
        } else {
          if (oldGoodsBook === data.MAXGoodsBookName && data.MAXGoodsBookName !== '') {
            sumCount += data.MAXCount;
            sumMoney += data.MAXAmount;
          } else {
            goods.push(new GoodsInfo(oldGoodsBook, sumCount, sumMoney));
            sumCount = data.MAXCount;
            sumMoney = data.MAXAmount;
            oldGoodsBook = data.MAXGoodsBookName;
          }
        }
        goods.push(data);
        allSumCount += data.MAXCount;
        allSumMoney += data.MAXAmount;
      });
      if (goods.length !== 0) {
        goods.push(new GoodsInfo(oldGoodsBook, sumCount, sumMoney));
      }
      goods.push(new GoodsInfo(null, allSumCount, allSumMoney));
      return goods;
    }

    // 病区领用单查询统计 过滤数组 拼接数据
    function handleReportForGoodsBook(result) {
      var goods = [];
      var allSumCount = 0;
      var allSumMoney = 0;
      result.forEach(function (data) {
        goods.push(data);
        allSumCount += data.MAXCount;
        allSumMoney += data.MAXAmount;
      });
      goods.push(new GoodsInfo(null, allSumCount, allSumMoney));
      return goods;
    }

    // 领用明细查询 过滤数组 拼接数据
    function handleReportForPackageDrawQuery(result) {
      var goods = [];
      var allSumCount = 0;
      var allSumMoney = 0;

      var deptNameArr = [];
      var deptDataInfo = {};
      result.forEach(function (data, index) {
        allSumCount += data.Counts;
        allSumMoney += data.Amount;

        var DeptName = data.DeptName.trim();
        if (deptNameArr.indexOf(DeptName) === -1) {
          deptNameArr.push(DeptName);
          deptDataInfo[DeptName] = [];
          deptDataInfo[DeptName].sumCount = 0;
          deptDataInfo[DeptName].sumMoney = 0;
        }
        deptDataInfo[DeptName].push(data);
        deptDataInfo[DeptName].sumCount += data.Counts;
        deptDataInfo[DeptName].sumMoney += data.Amount;
      });
      Object.keys(deptDataInfo).forEach(function (key) {
        deptDataInfo[key].push(new GetPackageInfo('科室 总计', deptDataInfo[key].sumCount, deptDataInfo[key].sumMoney));
        goods = goods.concat(deptDataInfo[key]);
      });
      goods.push(new GetPackageInfo('总计', allSumCount, allSumMoney));
      return goods;
    }

    function GetPackageInfo(oldDeptName, sumCount, sumMoney) {
      this.Amount = sumMoney;
      this.Counts = sumCount;
      this.DeptID = '';
      this.DeptName = '';
      this.PackageCode = '';
      this.PackageID = '';
      this.PackageName = oldDeptName;
      this.Price = '';
      this.Spec = '';
      this.Unit = '';
      this.isGoodsBookSumTr = (oldDeptName.indexOf('科室') !== -1);
      this.isAllSumTr = !this.isGoodsBookSumTr;
    }

    function GoodsInfo(goodsBookName, sumCount, sumMoney) {
      this.MAXDeptAccountName = '';
      this.MAXDeptAccountName = '';
      this.MAXGoodsBookName = '';
      this.GoodsID = '';
      this.MAXGoodName = (goodsBookName ? goodsBookName + '小计' : '总计');
      this.MAXGoodsSpec = '';
      this.MAXBoxUnit = '';
      this.LatestPrice = '';
      this.MAXCount = sumCount;
      this.MAXAmount = sumMoney;
      this.MAXCardNumber = '';
      this.MAXChargeCode = '';
      this.isGoodsBookSumTr = !!goodsBookName;
      this.isAllSumTr = !goodsBookName;
    }

    // 设置翻页的按钮是否可按
    function setToolsClass(firstPages, prePages, nextPages, lastPages) {
      booksApplyAnalyzeVm.firstPages = firstPages;
      booksApplyAnalyzeVm.prePages = prePages;
      booksApplyAnalyzeVm.nextPages = nextPages;
      booksApplyAnalyzeVm.lastPages = lastPages;
    }

    // 查询供应科室信息
    function getProviderDeptInfo(api, booksapplyanalyzeVm) {
      api.getOutDTODept({
        className: 'OrganizationManager',
        method: 'GetOutDTODept',
        ksdm: runtimeParam.Openparm.ProviderDept
      }).then(function (jsonResult) {

        if (jsonResult.issuccess !== 0) {
          return Promise.reject('获取信息失败');
        }
        runtimeParam.providerDept = JSON.parse(jsonResult.result);

        //判断当前登录科室 是否是供应科室
        if (runtimeParam.currentDept.DeptAccountID === runtimeParam.providerDept.DeptAccountID) {
          booksapplyanalyzeVm.isProviderDept = true;
        } else {
          booksapplyanalyzeVm.isProviderDept = false;
          booksapplyanalyzeVm.deptAccountName = runtimeParam.currentDept.Ksmc.trim();
          booksapplyanalyzeVm.deptAccountID = runtimeParam.currentDept.Ksdm;
        }

      })['catch'](function (ex) {
        tools.handleError(ex)
      });

      $('#reportTools').width($('#reportContent').width() + 2);
    }

    // 如果是领用明细查询 查询大类信息
    function getPackageBigList(booksApplyAnalyzeVm) {
      var HaveStock = new Condition("HaveStock", null, "Equal", 1, "Boolean"); // 是否有效
      api.getPackageBigCats({
        className: 'SysPackageBigCatManager',
        method: 'GetPackageBigCats',
        condition: JSON.stringify(HaveStock)
      }).then(function (jsonResult) {
        if (jsonResult.issuccess !== 0) {
          return Promise.reject('获取数据失败');
        }

        var result = JSON.parse(jsonResult.result);
        booksApplyAnalyzeVm.packageBigList.pushArray(result);
      })['catch'](function (ex) {
        tools.handleError(ex);
      });
    }

    function initQueryCondition(booksapplyanalyzeVm) {
      booksapplyanalyzeVm.startTime = new Date((new Date()).valueOf() - 1000 * 60 * 60 * 24).format('yyyy-MM-dd'); // 昨天
      booksapplyanalyzeVm.endTime = new Date().format('yyyy-MM-dd'); // 今天
      booksapplyanalyzeVm.$watch('deptAccountName', function (value) {
        if (value === '') {
          booksapplyanalyzeVm.deptAccountID = '';
        }
      });
      booksapplyanalyzeVm.$watch('goodsBookName', function (value) {
        if (value === '') {
          booksapplyanalyzeVm.goodsBookID = '';
        }
      });
      booksapplyanalyzeVm.$watch('goodsName', function (value) {
        if (value === '') {
          booksapplyanalyzeVm.goodsID = '';
        }
      });

      // 查询供应科室信息
      getProviderDeptInfo(api, booksapplyanalyzeVm);
      // 如果是领用明细查询 查询大类信息
      if (booksapplyanalyzeVm.reportType === 'packagedrawquery') {
        getPackageBigList(booksApplyAnalyzeVm);
      }
    }

    function defineFilters() {
      avalon.filters.showValue = function (value, index, key) {
        if (index === 0) {
          return value;
        }
        if (booksApplyAnalyzeVm.goods[index - 1][key] === booksApplyAnalyzeVm.goods[index][key]) {
          return '';
        } else {
          return value;
        }
      };
    }

    function initReportContentScroll(runtimeParam, booksApplyAnalyzeVm) {
      var timeFlag = {};
      var reportContent = $('#reportContent');
      var nScrollHeight = 0; //滚动距离总长(注意不是滚动条的长度)
      var nScrollTop = 0; //滚动到的当前位置
      var nDivHeight = reportContent.height();
      runtimeParam.canScroll = true;

      reportContent.scroll(function () {
        // 延时加载
        tools.throttle(timeFlag, function () {
          nScrollHeight = reportContent[0].scrollHeight; //滚动距离总长(注意不是滚动条的长度)
          nScrollTop = reportContent[0].scrollTop; //滚动到的当前位置
          // 向下翻页
          if (nScrollTop + nDivHeight >= (nScrollHeight - 5) && runtimeParam.canScroll &&
            !booksApplyAnalyzeVm.isShowPackageDrawDetail) {
            runtimeParam.canScroll = false;
            if (booksApplyAnalyzeVm.pages < booksApplyAnalyzeVm.counts) {
              booksApplyAnalyzeVm.pages++;
              paging(booksApplyAnalyzeVm, booksApplyAnalyzeVm.goods, runtimeParam.goods, booksApplyAnalyzeVm.size);
            }
          }
          // 向上翻页
          // if (nScrollTop === 0 && booksApplyAnalyzeVm.pages > 1 && canScroll) {
          //     canScroll = false;
          //     booksApplyAnalyzeVm.pages--;
          //     paging(booksApplyAnalyzeVm, booksApplyAnalyzeVm.goods, runtimeParam.goods, booksApplyAnalyzeVm.size, true);
          // }
          setTimeout(function () {
            runtimeParam.canScroll = true;
          }, 1000);
        });
      });
    }

    function chooseTableContent(reportType, htmlTemp) {
      var newHtmlTemp;
      switch (reportType) {
        // 单一科室所有账册查询
        case 'booksapplyanalyze':
          newHtmlTemp = htmlTemp.replace('${table}', singleDeptApplyTemp);
          break;
          // 病区领用单
        case 'wardapplyanalyze':
          newHtmlTemp = htmlTemp.replace('${table}', goodsBookApplyTemp);
          break;
          // 病区领用单
        case 'packagedrawquery':
          newHtmlTemp = htmlTemp.replace('${table}', packageDrawQuery + packageDrawQueryDetailTemp);
          break;
      }
      return newHtmlTemp;
    }

    var init = function ($main, param) {
      var newHtmlTemp = chooseTableContent(param.reportType, htmlTemp); // 设置表单的内容
      $main.append(newHtmlTemp);

      booksApplyAnalyzeVm = tools.initAvalonVm(avalon, getVmOption(), ".books-apply-analyze");
      booksApplyAnalyzeVm.breadcrumb = param.breadcrumb;
      booksApplyAnalyzeVm.reportType = param.reportType;

      runtimeParam = getRuntimeParam();
      runtimeParam.showMenu = param.showMenu;
      runtimeParam.checkBreadcrumb = param.checkBreadcrumb;
      runtimeParam.Openparm = param.Openparm; // 初始化参数
      runtimeParam.currentDept = JSON.parse(localStorage.getItem('deptInfo'));

      setTimeout(function () {
        laydate({
          elem: '#startTime'
        });
        laydate({
          elem: '#endTime'
        });
      }, 200);

      initQueryCondition(booksApplyAnalyzeVm);
      defineFilters(); // 过滤器
      initReportContentScroll(runtimeParam, booksApplyAnalyzeVm); // 设置 报表滚动事件
    };
    return {
      init: init
    }
  });